/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.zmc.common.utils;

import com.alibaba.fastjson2.JSON;
import com.zmc.common.constant.ResponseConstants;
import com.zmc.common.exception.base.ThirdBaseException;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 返回数据
 *
 * @author Mark sunlightcs@gmail.com
 */
public class R extends HashMap<String, Object> {

	public static final Logger log = LoggerFactory.getLogger(R.class);
	private static final long serialVersionUID = 1L;
	
	public R() {
		put(ResponseConstants.CODE_KEY, ResponseConstants.CODE_VALUE);
		put(ResponseConstants.MSG_KEY, ResponseConstants.MSG_VALUE);
	}
	
	public static R error() {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常，请联系管理员");
	}
	
	public static R error(String msg) {
		return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.put(ResponseConstants.CODE_KEY, code);
		r.put(ResponseConstants.MSG_KEY, msg);
		return r;
	}

	public static R ok(String msg) {
		R r = new R();
		r.put(ResponseConstants.MSG_KEY, msg);
		return r;
	}
	
	public static R page(PageUtils page) {
		R r = new R();
		r.put(ResponseConstants.TOTAL_KEY, page.getTotalCount());
		r.put(ResponseConstants.ROWS_KEY, page.getList());
		return r;
	}

	public static R page(List<?> list) {
		R r = new R();
		r.put("total", list.size());
		r.put("rows", list);
		return r;
	}

	public static R ok(Object o) {
		R r = new R();
		r.put(ResponseConstants.DATA_KEY, o);
		return r;
	}

	public static R ok(Map<String, Object> map) {
		R r = new R();
		r.putAll(map);
		return r;
	}
	
	public static R ok() {
		return new R();
	}

	@Override
	public R put(String key, Object value) {
		super.put(key, value);
		return this;
	}

	public R put(Map<String, Object> map) {
		super.putAll(map);
		return this;
	}

	public void valid() {
		int code = Integer.parseInt(this.get(ResponseConstants.CODE_KEY).toString());
		if (ResponseConstants.CODE_VALUE != code) {
			log.error("三方调用异常，result:" + JSON.toJSONString(this));
			throw new ThirdBaseException(this.get(ResponseConstants.MSG_KEY).toString());
		}
	}
}
